/**
 * 个人用户管理接口
 *
 * */

import {
  searchMobileUser,
  addMobileUser,
  deleteMobileUser,
  editMobileUser,
  getMobileUserDetail
} from "@/services/userManage";

export default {
  namespace: "userManage",

  state: {
    mobileUser: {
      content: [],
      mobileUserDetail: {}
    }
  },

  effects: {
    *searchMobileUser({ payload }, { call, put, select }) {
      const response = yield call(searchMobileUser, payload);
      if (!response) return;
      yield put({
        type: "saveState",
        payload: { mobileUser: response.data }
      });
    },

    *addMobileUser({ payload }, { call, put, select }) {
      const response = yield call(addMobileUser, payload);
      if (!response) return;
    },

    *editMobileUser({ payload }, { call, put, select }) {
      const { fields, selectedIndex } = payload;
      const { mobileUser } = yield select(state => state.userManage);
      const response = yield call(editMobileUser, fields);
      if (!response) return;
      const newMobileUser = {
        ...mobileUser.content[selectedIndex],
        ...fields
      };
      mobileUser.content.splice(selectedIndex, 1, newMobileUser);
      yield put({
        type: "saveState",
        payload: { mobileUser }
      });
    },

    *deleteMobileUser({ payload }, { call, put, select }) {
      const { mobileUserId, index } = payload;
      const { mobileUser } = yield select(state => state.userManage);
      const response = yield call(deleteMobileUser, { mobileUserId });
      if (!response) return;
      const newMobileUser = { ...mobileUser };
      newMobileUser.content.splice(index, 1);
      newMobileUser.totalElements -= 1;
      yield put({
        type: "saveState",
        payload: { mobileUser: newMobileUser }
      });
    },

    *getMobileUserDetail({ payload }, { call, put, select }) {
      const response = yield call(getMobileUserDetail, payload);
      if (!response) return;
      yield put({
        type: "saveState",
        payload: { mobileUserDetail: response.data }
      });
    }
  },

  reducers: {
    saveState(state, action) {
      return {
        ...state,
        ...action.payload
      };
    }
  }
};
